import React, { useEffect, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import axios from 'axios';
import UserLayout from '../user/UserLayout';
import networkService from '../../services/network';
import Toast from '../../components/Toast.js';
import PaginationComponent from '../network/NetworkHome/components/PaginationComponent.js';
import './myDownload.css';

const API_BASE_URL = 'http://117.72.106.234:8080/api';

// 创建axios实例
const api = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器 - 添加token
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

const MyDownloads = () => {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState('purchased'); // purchased, purchase-history, download-history
  const [purchases, setPurchases] = useState([]);
  const [purchaseHistory, setPurchaseHistory] = useState([]);
  const [downloadHistory, setDownloadHistory] = useState([]);
  const [userNetworks, setUserNetworks] = useState([]);
  const [selectedNetworks, setSelectedNetworks] = useState({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [showDownloadModal, setShowDownloadModal] = useState(false);
  const [selectedResource, setSelectedResource] = useState(null);
  const [toast, setToast] = useState({ show: false, message: '' });
  
  // 分页相关
  const [purchaseHistoryPage, setPurchaseHistoryPage] = useState({
    pageNum: 1,
    pageSize: 20,
    total: 0,
    totalPages: 0
  });
  
  const [downloadHistoryPage, setDownloadHistoryPage] = useState({
    pageNum: 1,
    pageSize: 20,
    total: 0,
    totalPages: 0
  });

  useEffect(() => {
    const token = localStorage.getItem('token');
    if (!token) {
      navigate('/login', { state: { from: '/my-downloads' } });
      return;
    }

    loadUserNetworks();
    loadPurchasedResources();
  }, [navigate]);

  useEffect(() => {
    if (activeTab === 'purchase-history') {
      loadPurchaseHistory(purchaseHistoryPage.pageNum);
    } else if (activeTab === 'download-history') {
      loadDownloadHistory(downloadHistoryPage.pageNum);
    }
  }, [activeTab]);

  // 加载用户加入的局域网列表
  const loadUserNetworks = async () => {
    try {
      const response = await networkService.getUserNetworks('joined');
      if (response.data.code === 200) {
        setUserNetworks(response.data.data);
      }
    } catch (error) {
    }
  };

  // 加载已购买资源列表
  const loadPurchasedResources = async () => {
    try {
      setLoading(true);
      const response = await api.get('/resource/purchase/history', {
        params: { pageNum: 1, pageSize: 100 } // 获取较多数据以显示所有已购买资源
      });
      
      if (response.data.code === 200) {
        setPurchases(response.data.data.purchases || []);
      } else {
        setError('获取已购买资源失败');
      }
    } catch (err) {
      setError('获取已购买资源失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  // 加载购买历史
  const loadPurchaseHistory = async (pageNum = 1, pageSize = 20) => {
    try {
      setLoading(true);
      const response = await api.get('/resource/purchase/history', {
        params: { pageNum, pageSize }
      });
      
      if (response.data.code === 200) {
        setPurchaseHistory(response.data.data.purchases || []);
        setPurchaseHistoryPage({
          pageNum: response.data.data.pageNum,
          pageSize: response.data.data.pageSize,
          total: response.data.data.total,
          totalPages: response.data.data.totalPages
        });
      }
    } catch (err) {
      setError('获取购买历史失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载下载历史
  const loadDownloadHistory = async (pageNum = 1, pageSize = 20) => {
    try {
      setLoading(true);
      const response = await api.get('/resource/download/history', {
        params: { pageNum, pageSize }
      });
      
      if (response.data.code === 200) {
        setDownloadHistory(response.data.data.downloads || []);
        setDownloadHistoryPage({
          pageNum: response.data.data.pageNum,
          pageSize: response.data.data.pageSize,
          total: response.data.data.total,
          totalPages: response.data.data.totalPages
        });
      }
    } catch (err) {
      setError('获取下载历史失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理购买历史分页变化
  const handlePurchaseHistoryPaginationChange = (page, pageSize) => {
    loadPurchaseHistory(page, pageSize);
  };

  // 处理下载历史分页变化
  const handleDownloadHistoryPaginationChange = (page, pageSize) => {
    loadDownloadHistory(page, pageSize);
  };

  // 显示Toast消息
  const showToast = (message) => {
    setToast({ show: true, message });
  };

  // 关闭Toast
  const closeToast = () => {
    setToast({ show: false, message: '' });
  };

  // 显示下载选项弹窗
  const showDownloadOptions = (resource) => {
    showToast("禁止把种子分享给其他人！");
    setSelectedResource(resource);
    setShowDownloadModal(true);
  };

  // 处理下载
  const handleDownload = async (isPublic = false) => {
    if (!selectedResource) return;

    try {
      let url;
      
      if (isPublic) {
        url = `${API_BASE_URL}/resource/download/public/${selectedResource.resourceId}`;
      } else {
        const networkId = selectedNetworks[selectedResource.resourceId];
        if (!networkId) {
          showToast('请选择一个局域网进行下载');
          return;
        }
        url = `${API_BASE_URL}/resource/download/network/${selectedResource.resourceId}/${networkId}`;
      }
      
      const response = await api.get(url, { responseType: 'blob' });

      // 创建下载链接
      const blobUrl = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = blobUrl;
      link.setAttribute('download', `${selectedResource.resourceTitle}.torrent`);
      document.body.appendChild(link);
      link.click();
      link.remove();
      
      window.URL.revokeObjectURL(blobUrl);
      setShowDownloadModal(false);
      
      // 刷新下载历史
      if (activeTab === 'download-history') {
        loadDownloadHistory(downloadHistoryPage.pageNum);
      }
    } catch (err) {
      if (err.response && err.response.data) {
        const reader = new FileReader();
        reader.onload = function() {
          try {
            const errorData = JSON.parse(reader.result);
            showToast(errorData.message || '下载失败，请稍后再试');
          } catch (e) {
            showToast('下载失败，请稍后再试');
          }
        };
        reader.readAsText(err.response.data);
      } else {
        showToast('下载失败，请稍后再试');
      }
    }
  };

  // 渲染下载选项弹窗
  const renderDownloadModal = () => {
    if (!showDownloadModal || !selectedResource) return null;

    return (
      <div className="download-modal-overlay" onClick={() => setShowDownloadModal(false)}>
        <div className="download-modal" onClick={(e) => e.stopPropagation()}>
          <div className="download-modal-header">
            <h3>选择下载方式</h3>
            <button className="close-btn" onClick={() => setShowDownloadModal(false)}>×</button>
          </div>
          
          <div className="download-modal-content">
            <div className="resource-info">
              <img 
                src={selectedResource.resourceCoverUrl || '/default-cover.jpg'} 
                alt={selectedResource.resourceTitle}
                onError={(e) => { e.target.src = '/default-cover.jpg' }}
              />
              <span>{selectedResource.resourceTitle}</span>
            </div>
            
            <div className="download-options">
              <div className="download-option">
                <label>局域网下载：</label>
                <select 
                  value={selectedNetworks[selectedResource.resourceId] || ''}
                  onChange={(e) => setSelectedNetworks({
                    ...selectedNetworks,
                    [selectedResource.resourceId]: e.target.value
                  })}
                >
                  <option value="">-- 选择局域网 --</option>
                  {userNetworks.map(network => (
                    <option key={network.networkId} value={network.networkId}>
                      {network.name}
                    </option>
                  ))}
                </select>
                <button 
                  className="download-btn network-download"
                  onClick={() => handleDownload(false)}
                  disabled={!selectedNetworks[selectedResource.resourceId]}
                >
                  局域网下载
                </button>
              </div>
              
              <div className="download-option">
                <label>公网下载：</label>
                <button 
                  className="download-btn public-download"
                  onClick={() => handleDownload(true)}
                >
                  公网下载
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  };

  // 渲染已购买资源列表
  const renderPurchasedResources = () => {
    if (purchases.length === 0) {
      return (
        <div className="empty-state">
          <p>您还没有购买任何资源</p>
          <Link to="/categories" className="browse-link">浏览资源</Link>
        </div>
      );
    }

    return (
      <div className="resources-list">
        {purchases.map(purchase => (
          <div key={purchase.purchaseId} className="resource-item">
            <div className="resource-cover">
              <img 
                src={purchase.resourceCoverUrl || '/default-cover.jpg'} 
                alt={purchase.resourceTitle}
                onError={(e) => { e.target.src = '/default-cover.jpg' }}
              />
            </div>
            
            <div className="resource-info">
              <h3 className="resource-title">
              {purchase.resourceTitle.length > 20 ? purchase.resourceTitle.substring(0, 20) + '...' :purchase.resourceTitle}
                <Link to={`/resource/detail/${purchase.resourceId}`}>
                  {purchase.resourceTitle}
                </Link>
              </h3>
              <div className="resource-meta">
                <span className="purchase-time">
                  获取时间：{new Date(purchase.purchaseTime).toLocaleString()}
                </span>
                <span className="points-paid">
                  {purchase.pointsPaid === 0 ? '免费获取' : `花费 ${purchase.pointsPaid} 积分`}
                </span>
              </div>
            </div>
            
            <div className="resource-actions">
              <button 
                className="download-btn primary"
                onClick={() => showDownloadOptions(purchase)}
              >
                <span className="stat-icon">⬇️</span> 下载
              </button>
              <Link 
                to={`/resource/detail/${purchase.resourceId}`}
                className="detail-link"
              >
                查看详情
              </Link>
            </div>
          </div>
        ))}
      </div>
    );
  };

  // 渲染购买历史
  const renderPurchaseHistory = () => {
    if (purchaseHistory.length === 0) {
      return (
        <div className="empty-state">
          <p>暂无购买历史记录</p>
        </div>
      );
    }

    return (
      <>
        <div className="history-list">
          {purchaseHistory.map(purchase => (
            <div key={purchase.purchaseId} className="history-item">
              <div className="item-info">
                <span className="item-title">{purchase.resourceTitle}</span>
                <span className="item-time">{new Date(purchase.purchaseTime).toLocaleString()}</span>
              </div>
              <div className="item-detail">
                <span className={`points ${purchase.pointsPaid === 0 ? 'free' : ''}`}>
                  {purchase.pointsPaid === 0 ? '免费' : `${purchase.pointsPaid} 积分`}
                </span>
              </div>
            </div>
          ))}
        </div>
        
        {purchaseHistoryPage.totalPages > 1 && (
          <div className="pagination-container">
            <PaginationComponent
              current={purchaseHistoryPage.pageNum}
              pageSize={purchaseHistoryPage.pageSize}
              total={purchaseHistoryPage.total}
              onChange={handlePurchaseHistoryPaginationChange}
            />
          </div>
        )}
      </>
    );
  };

  // 渲染下载历史
  const renderDownloadHistory = () => {
    if (downloadHistory.length === 0) {
      return (
        <div className="empty-state">
          <p>暂无下载历史记录</p>
        </div>
      );
    }

    return (
      <>
        <div className="history-list">
          {downloadHistory.map(download => (
            <div key={download.downloadId} className="history-item">
              <div className="item-info">
                <span className="item-title">资源ID: {download.resourceId}</span>
                <span className="item-time">{new Date(download.downloadTime).toLocaleString()}</span>
              </div>
              <div className="item-detail">
                <span className="network-info">
                  {download.networkId ? `局域网ID: ${download.networkId}` : '公网下载'}
                </span>
              </div>
            </div>
          ))}
        </div>
        
        {downloadHistoryPage.totalPages > 1 && (
          <div className="pagination-container">
            <PaginationComponent
              current={downloadHistoryPage.pageNum}
              pageSize={downloadHistoryPage.pageSize}
              total={downloadHistoryPage.total}
              onChange={handleDownloadHistoryPaginationChange}
            />
          </div>
        )}
      </>
    );
  };

  if (loading && activeTab === 'purchased') {
    return (
      <UserLayout>
        <div className="loading-container">
          <div className="loading-spinner"></div>
          <p>加载中...</p>
        </div>
      </UserLayout>
    );
  }

  return (
    <UserLayout>
      <div className="my-downloads-container">
        <h1 className="page-title">我的下载</h1>
        
        <div className="tabs">
          <button 
            className={`tab-btn ${activeTab === 'purchased' ? 'active' : ''}`}
            onClick={() => setActiveTab('purchased')}
          >
            已入库资源
          </button>
          <button 
            className={`tab-btn ${activeTab === 'purchase-history' ? 'active' : ''}`}
            onClick={() => setActiveTab('purchase-history')}
          >
            购买历史
          </button>
          <button 
            className={`tab-btn ${activeTab === 'download-history' ? 'active' : ''}`}
            onClick={() => setActiveTab('download-history')}
          >
            下载历史
          </button>
        </div>
        
        <div className="tab-content">
          {error && <div className="error-message">{error}</div>}
          
          {activeTab === 'purchased' && renderPurchasedResources()}
          {activeTab === 'purchase-history' && renderPurchaseHistory()}
          {activeTab === 'download-history' && renderDownloadHistory()}
        </div>
        
        {renderDownloadModal()}
        
        {/* Toast组件 */}
        {toast.show && (
          <Toast 
            message={toast.message} 
            onClose={closeToast}
          />
        )}
      </div>
    </UserLayout>
  );
};

export default MyDownloads;